#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
 
#define SOCKET_PATH "/tmp/unix_socket"
#define BUFFER_SIZE 1024
 
int main() {
    int server_fd, new_socket;
    struct sockaddr_un address;
    int addrlen = sizeof(address);
    char buffer[BUFFER_SIZE] = {0};
    int opt = 1;
    int addrlen_size;
 
    // 创建套接字
    if ((server_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }
 
    // 设置套接字选项，允许重用地址和端口
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("setsockopt");
        close(server_fd);
        exit(EXIT_FAILURE);
    }
 
    // 清除地址结构
    memset(&address, 0, sizeof(struct sockaddr_un));
 
    // 设置地址和端口
    address.sun_family = AF_UNIX;
    strncpy(address.sun_path, SOCKET_PATH, sizeof(address.sun_path) - 1);
 
    // 绑定套接字到地址
    if (bind(server_fd, (struct sockaddr *)&address, sizeof(struct sockaddr_un)) < 0) {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }
 
    // 监听连接
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        close(server_fd);
        unlink(SOCKET_PATH); // 删除套接字文件
        exit(EXIT_FAILURE);
    }
 
    // 接受客户端连接
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen_size)) < 0) {
        perror("accept");
        close(server_fd);
        unlink(SOCKET_PATH); // 删除套接字文件
        exit(EXIT_FAILURE);
    }
 
    // 读取客户端发送的数据
    int valread = read(new_socket, buffer, BUFFER_SIZE);
    printf("Received: %s\n", buffer);
 
    // 发送响应给客户端
    char *hello = "Hello from server";
    send(new_socket, hello, strlen(hello), 0);
    printf("Hello message sent\n");
 
    // 关闭套接字
    close(new_socket);
    close(server_fd);
    unlink(SOCKET_PATH); // 删除套接字文件
 
    return 0;
}